<template>
  <page-header-wrapper :title="false">
    <a-card title="店面详情">
      <template #extra> <a-button type="primary" @click="handleEdit()">编辑店面</a-button></template>
      <a-descriptions bordered title="" size="small">
        <a-descriptions-item label="店名" :span="3">{{ storeDetail?.storeName }}</a-descriptions-item>
        <a-descriptions-item label="联系电话" :span="3">{{ storeDetail?.phone }}</a-descriptions-item>
        <a-descriptions-item label="省" :span="3">{{ storeDetail?.province }}</a-descriptions-item>
        <a-descriptions-item label="市" :span="3">{{ storeDetail?.city }}</a-descriptions-item>
        <a-descriptions-item label="地址" :span="3">{{ storeDetail?.address }}</a-descriptions-item>
        <a-descriptions-item label="定位地址" :span="3">
          {{ storeDetail.gpsAddress }}
          <a-tag color="#428bca" @click="handleMap(storeDetail)">编辑</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="店面状态" :span="3">
          <a-tag color="#82af6f" v-if="storeDetail.storeStatus == 1">营业中</a-tag>
          <a-tag color="#abbac3" v-else>停业</a-tag>
        </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card title="柜组信息">
      <template #extra>
        <div style="display:flex">
          <a-button type="primary" icon="plus" @click="handleGroup()">新增柜组</a-button>
          <a-tooltip style="margin-left:10px">
            <template #title> 数据导出</template>
            <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button> </a-tooltip
          >  
        </div>  
      </template>
      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data-source="loadData"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <span slot="status" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.counterStatus == 1">启用中</a-tag>
            <a-tag color="#abbac3" v-else>禁用</a-tag>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" @click="handleGroupEdit(record)">编辑</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <group-form
      ref="groupModal"
      :visible="groupVisible"
      :loading="groupLoading"
      :model="mdll"
      @cancel="handleGroupCancel"
      @ok="handleGroupOk"
    />
  </page-header-wrapper>
</template>

<script>
import CreateForm from './CreateForm'
import GroupForm from './groupForm'
import {
  getStoreUsingGET,
  updateStoreUsingPOST,
  addStCounterUsingPOST,
  updateStCounterUsingPOST,
  getStCounterListUsingPOST,
  exportStCounterUsingPOST
} from '@/api/api/mendianguanli.ts'
export default {
  name: 'ShopDetail',
  components: {
    CreateForm,
    GroupForm,
  },
  data() {
    return {
      mdll: null,
      mdl: null,
      visible: false,
      groupVisible: false,
      groupLoading: false,
      storeDetail: {},
      confirmLoading: false,
      // 查询参数
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        status: '',
      },
      columns: [
        {
          title: '柜组ID',
          dataIndex: 'id',
        },
        {
          title: '柜组名称',
          dataIndex: 'counterName',
        },
        {
          title: '状态',
          dataIndex: 'counterStatus',
          needTotal: true,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      loading: false,
      pagination: {},
    }
  },
  mounted() {
    this.getDetail()
    this.handleSearch(this.queryParam)
  },
  methods: {
    handleExpert(params){
      exportStCounterUsingPOST({ ...params, storeId: this.$route.params.id }).then((res) => {
          const blob = new Blob([res], {
            type: 'application/vnd.ms-excel;charset=utf-8',
          })
          const filename = '柜组列表' + '.xlsx'
          // 将blob对象转为一个URL
          var blobURL = window.URL.createObjectURL(blob)
          // 创建一个a标签
          var tempLink = document.createElement('a')
          // 隐藏a标签
          tempLink.style.display = 'none'
          // 设置a标签的href属性为blob对象转化的URL
          tempLink.href = blobURL
          // 给a标签添加下载属性
          tempLink.setAttribute('download', filename)
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 将a标签添加到body当中
          document.body.appendChild(tempLink)
          // 启动下载
          tempLink.click()
          // 下载完毕删除a标签
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
          this.$message.success('导出成功~')
        })  
    },
    handleSearch(params) {
      this.loading = true
      getStCounterListUsingPOST({ ...params, storeId: this.$route.params.id })
        .then((res) => {
          this.loading = false
          this.loadData = res.data.list
          this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch(() => {
          this.loading = false
          this.$message.error('获取列表失败,请联系管理员')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition: this.queryParam.queryCondition,
        status: this.queryParam.status,
        date: this.queryParam.date,
      })
    },
    getDetail() {
      getStoreUsingGET({ id: this.$route.params.id })
        .then((res) => {
          this.storeDetail = res.data
        })
        .catch(() => {
          this.$message.error('获取详情失败,请联系管理员')
        })
    },
    handleMap(storeDetail) {
      this.$router.push({ path: `/shop/mapDetail/${storeDetail?.id}` })
    },
    handleGroup() {
      this.groupLoading = false
      this.groupVisible = true
      this.mdll = null
      const form = this.$refs.groupModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleEdit() {
      this.mdl = { ...this.storeDetail }
      this.confirmLoading = false
      this.visible = true
    },
    handleGroupEdit(record) {
      this.mdll = { ...record, counterStatus: Number(record.counterStatus) }
      this.groupVisible = true
    },
    handleOk() {
      this.visible = false
      this.confirmLoading = true
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.id > 0) {
            updateStoreUsingPOST({ ...values })
              .then(() => {
                this.getDetail()
                this.$message.success('修改成功')
              })
              .catch(() => {
                this.confirmLoading = false
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleGroupOk() {
      this.groupLoading = true
      const form = this.$refs.groupModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.id > 0) {
            updateStCounterUsingPOST({ ...values })
              .then(() => {
                this.groupLoading = false
                this.$message.success('修改成功')
                this.groupVisible = false
                this.handleSearch(this.queryParam)
              })
              .catch((error) => {
                this.groupLoading = false
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          } else {
            addStCounterUsingPOST({ ...values, storeId: this.$route.params.id })
              .then(() => {
                this.groupLoading = false
                this.groupVisible = false
                this.$message.success('添加成功')
                this.handleSearch(this.queryParam)
              })
              .catch((error) => {
                this.groupLoading = false
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          }
        } else {
          this.groupLoading = false
        }
      })
    },
    handleGroupCancel() {
      this.groupVisible = false
      const form = this.$refs.groupModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
  },
}
</script>
